﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Database;
using Communication;
using System.Net.Mail;
using System.Net;
using System.IO;

namespace WCFService
{
    public class LogicForumImp : NewLogicForumInterface
    {

        private DBmediator database = new DBmediator();
        private static List<string> forumsuserlist = new List<string>();
        private Boolean DirectorIsLogin;
        private Dictionary<string, UserPosition> userPositions = new Dictionary<string, UserPosition>();

        private List<string> cachedForbiddenWords;
        private int cachedForum = -1;
        // private List<string> alluserlist = new List<string>();

        public LogicForumImp()
        {
            //   this.database = new DBmediator();
            //createHTMLfromDatabase();
        }
        #region public method imp region
        #region finish

        public Thread BackFromPost(User user, int forumid, int subforumid, int Threadid)
        {//return null if its not good
            if (user == null || forumid < 0 || subforumid < 0 || Threadid < 0)
                return null;

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            SubForum sb = database.getSubForum(forumid, subforumid);
            if (sb == null)
                return null;
            Thread thread = sb.getThread(Threadid);
            return thread;
        }

        //==========================================back
        public SubForum BackFromThread(User user, int forumid, int subforumid)
        {//return null if wrong

            if (user == null || forumid < 0 || subforumid < 0)
                return null;

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            return database.getSubForum(forumid, subforumid);
        }

        public Forum BackFromSubForum(User user, int forumid)
        {//retrun null if wrong
            if (user == null || forumid < 0)
                return null;
            return database.getForum(forumid);
        }

        public Boolean Register(int forumid, string username, string firstname, string lastname, string password, string email)
        {


            //check that the client is not register allready
            if (CheckIfUserMember(forumid, username) == true)
            {
                return false;
            }
            //check that username and password not empty
            if (username.Equals("") || password.Equals(""))
                return false;
            //check that there is a forum with this id

            //check with nataly to change password to string


            // *********** Gilad's addition ************
            password = Server.Security.passwordEncryption(username, password);
            // *********** End Gilad's addition ************


            User newuser = database.registerUser(forumid, username, firstname, lastname, password, email);
            if (newuser == null)
                return false;
            Console.WriteLine("User {0} did register. to forum name : {1}", newuser.getUserName(), database.getForumTitle(forumid));
            Logger.log(string.Format("User {0} did register. to forum name : {1}", newuser.getUserName(), database.getForumTitle(forumid)));


            return true;

        }
        //function to do the register return true if its ok , and false if not
        //check if the name is not found allready at the database

        public int EditPost(User user, int forumid, int postid, string title, string body)
        { //function that will edit the post if the client can do it
            //and will refresh the client page after its done
            //return true if its succeceed else false

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return 1;

            //check if the client is register to the forum if not return false
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return 1;


            //check if the user is not the post creator

            if (!this.checkMessage(title + " " + body, forumid))
                return 2;



            if (database.changePostPermission(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, this.userPositions[user.getUserName() + " " + forumid].thread, postid, user) == false)
                return 1;

            database.setPostBody(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, this.userPositions[user.getUserName() + " " + forumid].thread, postid, body);
            database.setPostTitle(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, this.userPositions[user.getUserName() + " " + forumid].thread, postid, title);
            Console.WriteLine("User {0} edit a post with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} edit a post with title {1}.", user.getUserName(), title));

            return 0;
        }

        public int EditThread(User user, int forumid, int threadid, string title, string body)
        {//function that will edit the thread if the client can do it
            //and will refresh the client page after its done
            //return true if its succeceed else false

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return 1;

            //check if hes not a member of the forum
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return 1;

            if (!this.checkMessage(title + " " + body, forumid))
                return 2;


            //check the premmision

            if (database.changeThreadPermission(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, threadid, user) == false)
                return 1;

            //change the thread
            database.setThreadBody(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, threadid, body);
            database.setThreadTitle(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, threadid, title);
            Console.WriteLine("User {0} edit a thread with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} edit a thread with title {1}.", user.getUserName(), title));

            return 0;
        }

        //===========================================================================================================-add

        public Boolean AddForum(User user, string title, User ForumManager, int mods, int modCan, int modsDel, int notific, int mailAu, List<string> badWords)
        {//doing by the director
            if (CheckIfDirectorLogin(user) == false && !user.getUserName().Equals(database.getDirector().getUserName()))
                return false;
            if (database.addForumPermission(user) == false)
                return false;

            ForumManager.setPassword(Server.Security.passwordEncryption(ForumManager.getUserName(), ForumManager.getPassword()));

            int forumId = database.addForum(title, ForumManager, mods, modCan, modsDel, notific, mailAu);
            for (int i = 0; i < badWords.Count(); i++)
                database.addForbiddenWord(forumId, badWords.ElementAt(i));
            return true;
            //foreach (KeyValuePair<int, Forum> ForumPair in database.getForums())
            //{//go all the forum and find the user (administrator)
            //    foreach (KeyValuePair<string, User> UserPair in ForumPair.Value.getUsers())
            //    {
            //        if (UserPair.Key.Equals(ForumManager))
            //        {//if i found the user
            //            newadministrator = UserPair.Value;
            //            res=database.addForum(title,newadministrator);
            //            if (res != -1)
            //            {
            //                Console.WriteLine("User {0} add a new forum with title {1} and put {2} as a manager.", user.getUserName(), title,ForumManager);
            //                Logger.log(string.Format("User {0} add a new forum with title {1} and put {2} as a manager.", user.getUserName(), title,ForumManager));

            //                return true;
            //            }

            //        }
            //    }
            //}
            //  res= database.addForum(title, user);

            // return false;

        }

        public int AddSubForum(User user, int forumid, string title, string manager)
        { // add new subforum if the client can do it (got the premission)
            //and put the name of the moderator as a moderetor of this subforum
            //return true if succeced

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return 1;

            //check that the input is ok
            if (user == null || title.Equals("") || manager.Equals("") || forumid < 0)
                return 1;

            //check the premission of the client

            //check if hes not a member of the forum
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return 1;

            if (!this.checkMessage(title, forumid))
                return 2;


            //if (database.AddSubForumPermission(forumid,clientuser) == false)
            //  return false;
            if (CheckPermissionChangeModerator(forumid, user.getUserName()) == false)
                return 1;


            //check if the moderetor is a user at the forum
            if (database.isForumUser(forumid, manager) == false)
                return 1;

            int res = database.addSubForum(forumid, title);

            //add the new moderator to the subforum add 21/6/13
            //its made Ilya as a moderator for the new subforum automatic
            database.addSubForumModerator(forumid, res, manager);
            //end adding

            if (res == -1)
                return 1;
            Console.WriteLine("User {0} added a new subforum with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} added a new subforum with title {1}.", user.getUserName(), title));
            return 0;


        }

        public int AddThread(User user, int forumid, string title, string body)
        {

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return 1;

            //check that the input is ok
            if (user == null || title.Equals("") || body.Equals(""))
                return 1;
            //check if hes member of the forum
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return 1;

            if (!this.checkMessage(title + " " + body, forumid))
                return 2;

            if (database.addThreadPermission(forumid, user) == false)
                return 1;

            if (this.userPositions[user.getUserName() + " " + forumid].subForum == -1)
                return 1;

            int res = database.addThread(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, title, body, user);
            //check if there anyproblem with add the thread
            if (res == -1)
                return 1;

            Console.WriteLine("User {0} added a new Thread with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} added a new Thread with title {1}.", user.getUserName(), title));
            return 0;

        }

        public int webAddThread(string userName, int forumid, int sub, string title, string body)
        {
            if (!this.checkMessage(title + " " + body, forumid))
                return 2;
            return database.addThread(forumid, sub, title, body, getuser(forumid,userName));
        }


        public int AddPost(User user, int forumid, string title, string body)
        {

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return 1;

            //check that the input is ok
            if (user == null || title.Equals("") || body.Equals(""))
                return 1;
            //check if hes member
            if (CheckIfUserMember(forumid, user.getUserName()) == false)
                return 1;

            if (!this.checkMessage(title + " " + body, forumid))
                return 2;


            if (database.addPostPermission(forumid, user) == false)
                return 1;
            int res = database.addPost(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, this.userPositions[user.getUserName() + " " + forumid].thread, title, body, user);
            if (res == -1)//check if teh addpost succeced
                return 1;

            Console.WriteLine("User {0} added a new Post with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} added a new Post with title {1}.", user.getUserName(), title));

            return 0;
        }

        public int webAddPost(string userName, int forumid, int sub, int thread, string title, string body)
        {
            if (!this.checkMessage(title + " " + body, forumid))
                return 2;
            return database.addPost(forumid, sub, thread, title, body, getuser(forumid,userName));
        }

        public Boolean AddNewModeratorToSubForum(User user, int forumid, int subforumid, string moderetoruserName)
        {
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            //check that the input is ok
            if (user == null || subforumid < 0 || forumid < 0 || moderetoruserName.Equals(""))
                return false;


            //can do it only the manager of the forum 
            Boolean res = CheckPermissionChangeModerator(forumid, user.getUserName());
            if (res == false)
                return false;
            //check that username is user at the forum
            res = CheckIfUserMember(forumid, moderetoruserName);


            //then the client is the manager or the director of the forum


            res = database.addSubForumModerator(forumid, subforumid, moderetoruserName);
            if (res == false)
                return false;

            string subforumname = database.getSubForum(forumid, subforumid).getTitle();
            //or the director
            Console.WriteLine("User {0} promote {1} to a moderator of subforum {2}", user.getUserName(), moderetoruserName, subforumname);
            Logger.log(string.Format("User {0} promote {1} to a moderator of subforum {2}", user.getUserName(), moderetoruserName, subforumname));
            return true;



        }

        //=============================================================================================================remove
        public Boolean RemoveSubForum(User user, int forumid, int subforumid)
        {
            //remove the subforum from the forum if the client has the premission to do it
            //return true if succeced

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;


            //check if he have the premission
            if (CheckPermissionChangeModerator(forumid, user.getUserName()) == false)
                return false;
            //to get the title of the subforum
            SubForum sf = database.getSubForum(forumid, subforumid);
            if (sf == null)
                return false;
            String title = sf.getTitle();
            if (database.removeSubForum(forumid, subforumid) == false)
                return false;
            Console.WriteLine("User {0} remove a subforum with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} remove a new subforum with title {1}.", user.getUserName(), title));
            return true;


        }

        //remove the thread of the forum if client got premission , post at client position and the thread position
        public Boolean RemoveThread(User user, int forumid, int threadposition)
        {
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            if (database.changeThreadPermission(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, threadposition, user) == false)
                return false;

            //get the body
            SubForum sb = database.getSubForum(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum);
            if (sb == null)
                return false;
            Thread thread = sb.getThread(threadposition);
            if (thread == null)
                return false;
            String title = thread.getTitle();

            if (database.removeThread(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, threadposition) == false)
                return false;

            Console.WriteLine("User {0} remove a thread with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} remove a new thread with title {1}.", user.getUserName(), title));
            return true;
        }

        public Boolean RemovePost(User user, int forumid, int postposition)
        //remove the post of the forum if client got premission , post at client position and the post position
        {

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            if (database.changePostPermission(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, this.userPositions[user.getUserName() + " " + forumid].thread, postposition, user) == false)
                return false;

            //get the body
            Post post = database.getPost(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, this.userPositions[user.getUserName() + " " + forumid].thread, postposition);
            if (post == null)
                return false;
            String title = post.getTitle();

            if (database.removePost(forumid, this.userPositions[user.getUserName() + " " + forumid].subForum, this.userPositions[user.getUserName() + " " + forumid].thread, postposition) == false)
                return false;

            Console.WriteLine("User {0} remove a post with title {1}.", user.getUserName(), title);
            Logger.log(string.Format("User {0} remove a new post with title {1}.", user.getUserName(), title));
            return true;
        }

        //return true if the client can add the username as a moderator and did it
        //return false if its not succuced
        //only the manager of the forum can do it or the administrator

        public Boolean RemoveModerator(User user, int forumid, int subforumid, string moderatoruserName)
        {
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            //check  if client has the premission to remove
            Boolean res = CheckPermissionChangeModerator(forumid, user.getUserName());
            if (res == false)
                return false;


            //check that the number of moderator is higher then 1
            SortedDictionary<string, User> moderators = database.getSubForumModerators(forumid, subforumid);
            int numberofmoderator = moderators.Count;
            if (numberofmoderator < 2)
                return false;
            //remove the moderator
            string subForumName = database.getForum(forumid).getSubForum(subforumid).getTitle();
            res = database.removeSubForumModerator(forumid, subforumid, moderatoruserName);
            if (res == false)
                return false;

            Console.WriteLine("User {0} remove {1} to a moderator of subforum {2}", user.getUserName(), moderatoruserName, subForumName);
            Logger.log(string.Format("User {0} remove {1} to a moderator of subforum {2}", user.getUserName(), moderatoruserName, subForumName));
            return true;

        }

        //=========================================================================new assignment 2

        public Boolean ChangeTheSubForumModerator(User user, int forumid, int subforumid, string UserNametoRemove, string UserNametoAdd)
        {
            //change the moderator of the subforum , return true if did it
            //return false if dont have premisstion or someother problems

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            Boolean res = CheckPermissionChangeModerator(forumid, user.getUserName());
            if (res == false)
                return false;
            res = AddNewModeratorToSubForum(user, forumid, subforumid, UserNametoAdd);
            if (res == false)
                return false;
            res = RemoveModerator(user, forumid, subforumid, UserNametoRemove);
            if (res == false)
                return false;

            return true;
        }

        //=================================================================================reports

        public int SubForumMsgCount(User user, int forumid, int subforumid)
        {//only manager can do it if the user is not the manager i will return -1
            //return the number of thread and posts at the subforum

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return -1;


            int CountSumOfMsg = 0;
            //check if its the manager
            if (user == null || CheckPermissionChangeModerator(forumid, user.getUserName()) == false)
                return -1;

            //Thread thisthread;
            SortedDictionary<int, Thread> allsubforumthreads = database.getSubForumThreads(forumid, subforumid);
            if (allsubforumthreads != null)
            {
                foreach (Thread thisthread in allsubforumthreads.Values)
                {
                    //thisthread = pair.Value;
                    //maybe its null
                    if (thisthread != null)
                    {//if not i will count how many post he have
                        CountSumOfMsg++;
                        SortedDictionary<int, Post> allpost = thisthread.getPosts();
                        if (allpost != null)
                        {
                            foreach (Post post in allpost.Values)
                            {
                                if (post != null)
                                    CountSumOfMsg++;
                            }
                        }
                    }
                }
            }
            string subforumname = database.getForum(forumid).getSubForum(subforumid).getTitle();
            Console.WriteLine("User {0} check the numberof message at subforum {1}", user.getUserName(), subforumname);
            Logger.log(string.Format("User {0} check the numberof message at subforum {1}", user.getUserName(), subforumname));
            return CountSumOfMsg;
        }

        public int MemberMsgCount(User user, int forumid, string userName)
        //return the number of message a user did at the all the forums
        {//only manager can do it

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return -1;

            int countmembermsg = 0;
            //check that its the manager of the forum
            if (user == null || CheckPermissionChangeModerator(forumid, user.getUserName()) == false)
                return -1;

            //and eatch forum check how many massage he make

            Forum forum = database.getForum(forumid);

            if (CheckIfUserMember(forumid, userName) == true)
            {//if hes not a user at the forum he cant make msg there
                foreach (SubForum sb in forum.getSubForums().Values)
                {
                    if (sb != null)
                    {
                        foreach (Thread thread in sb.getThreads().Values)
                        {//for eacth thread
                            if (thread != null)
                            {
                                //check if he create the thread
                                User threaduser = thread.getUser();
                                if (threaduser.getUserName().Equals(userName))
                                    countmembermsg++;
                                foreach (Post post in thread.getPosts().Values)
                                {
                                    if (post != null)
                                    {//for eatch post if hes not null check if he post the post
                                        User postuser = post.getUser();
                                        if (postuser.getUserName().Equals(userName))
                                            countmembermsg++;
                                    }
                                }
                            }
                        }
                    }
                }
            }


            return countmembermsg;
        }

        public string getAllMemberRespondToAllThreads(User user, int forumid, int subforumid)
        {//can be done only by the manager or director

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return "";

            //check that its the manager of the forum
            if (user == null || CheckPermissionChangeModerator(forumid, user.getUserName()))
                return "";


            string res = "";

            SortedDictionary<string, string> alllistofrespond = new SortedDictionary<string, string>();
            //first one is the username second is the userlist that respond to him
            //check if the username got people allready
            SubForum sb = database.getSubForum(forumid, subforumid);
            if (sb == null)
                return "";

            foreach (Thread thread in sb.getThreads().Values)
            {
                if (thread != null)
                {//if he not null i will get all the people that post there and add it to 
                    string threadcreator = thread.getUser().getUserName();
                    //now get all the people who post at his thread
                    string peoplepost = getMembersResponedToThread(user, forumid, subforumid, thread.getId());
                    //now i will check if he allready have list
                    if (alllistofrespond.ContainsKey(threadcreator) == true)
                    {
                        string str = alllistofrespond[threadcreator];
                        peoplepost = peoplepost + " , " + str;
                        alllistofrespond.Remove(threadcreator);
                        alllistofrespond.Add(threadcreator, peoplepost);
                    }
                    else
                    {
                        alllistofrespond.Add(threadcreator, peoplepost);
                    }

                }
            }
            //now i need to get all to the same string

            foreach (KeyValuePair<string, string> pair in alllistofrespond)
            {
                //  string valuewithoutcoupling = removecoupling(pair.Value);
                string valuewithoutcoupling = pair.Value;
                res = res + " the people that respond to " + pair.Key + " threads are : " + valuewithoutcoupling + ".\r\n";
            }
            Console.WriteLine("User {0} get all the respond members", user.getUserName());
            Logger.log(string.Format("User {0} get all the respond members", user.getUserName()));

            return res;

        }

        public int getNumberOfForum(User user)
        {//only director can do it if wrong return -1

            //check user login
            if (CheckIfDirectorLogin(user) == false && (!user.getUserName().Equals(database.getDirector().getUserName())))
                return -1;

            //check its the director
            if (user == null || (!database.getDirector().getUserName().Equals(user.getUserName())))
                return -1;

            Console.WriteLine("User {0} get the number of all the forums at the server", user.getUserName());
            Logger.log(string.Format("User {0} get the number of all the forums at the server", user.getUserName()));
            return database.getNumOfForums();
        }

        //return the number of forum at database
        public int getNumberOfCommonUsers(User user)
        {//only director can do it , if wrong return -1

            //if (checkifdirectorlogin(user) == false)
            //  return -1;

            if (user == null || (!database.getDirector().getUserName().Equals(user.getUserName())))
                return -1;
            int commonuser = 0;
            //count common users
            /*
            SortedDictionary<string, User> forumsusers = new SortedDictionary<string, User>();

            foreach (KeyValuePair<int, Forum> ForumPair in database.getForums())
            {
                foreach (KeyValuePair<string, User> UserPair in ForumPair.Value.getUsers())
                {
                    if (!forumsusers.Contains(UserPair))
                        forumsusers.Add(UserPair.Key, UserPair.Value);
                    else
                    {
                        commonuser++;
                    }
                }
            }
            */

            List<string> emails = new List<string>();
            List<int> count = new List<int>();

            foreach (KeyValuePair<int, Forum> ForumPair in database.getForums())
            {
                foreach (KeyValuePair<string, User> UserPair in ForumPair.Value.getUsers())
                {
                    Console.WriteLine(UserPair.Value.getEmail() + " " + UserPair.Value.getUserName());
                    if (!emails.Contains(UserPair.Value.getEmail()))
                    {
                        emails.Add(UserPair.Value.getEmail());
                        count.Add(0);
                    }

                    else
                    {
                        if (count[emails.IndexOf(UserPair.Value.getEmail())] == 0)
                        {
                            commonuser++;
                            count[emails.IndexOf(UserPair.Value.getEmail())]++;
                        }
                    }
                }


            }



            //need to finish
            Console.WriteLine("User {0} get the number of common users at the forums", user.getUserName());
            Logger.log(string.Format("User {0} get the number of common users at the forums", user.getUserName()));
            return commonuser;
        }

        private SortedDictionary<string, User> getAllUsersOfTheForums()
        {//get all the users at the forum
            SortedDictionary<string, User> forumsusers = new SortedDictionary<string, User>();

            foreach (KeyValuePair<int, Forum> ForumPair in database.getForums())
            {
                foreach (KeyValuePair<string, User> UserPair in ForumPair.Value.getUsers())
                {
                    if (!forumsusers.Contains(UserPair))
                        forumsusers.Add(UserPair.Key, UserPair.Value);

                }
            }
            return forumsusers;
        }

        public string getstringCountsubForumMsg(User user, int forumid, int subforumid)
        {
            //return the subforum name and how many thread and post he have inside
            //string statMsg = "\r\nSubForum: " + sfTitle + "\r\nTotal Threads+Posts: " + res;

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return "";

            int res = SubForumMsgCount(user, forumid, subforumid);
            SubForum sb = database.getSubForum(forumid, subforumid);
            string subforumname = "";
            if (sb != null)
                subforumname = sb.getTitle();
            string statMsg = "\r\nSubForum: " + subforumname + "\r\nTotal Thread+Posts: " + res;
            /*
             *  string statMsg ="\r\nSubForum: ";
            statMsg+=subforumname;
            statMsg+="\r\nTotal Thread+Posts: ";
            statMsg+=res;
      */


            return statMsg;
        }
        //=============================================================================================================

        public string getstringCountMemberMsg(User user, int forumid, string userName)
        {//return the user name and how many thread and post he did
            // string statMsg = "User: " + userName + "\r\nTotal Publications(T\\P): " + res;

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return "";

            int res = MemberMsgCount(user, forumid, userName);
            string statMsg;
            if (res == -1)
                statMsg = "User: " + userName + "\r\nTotal Public Action(Threads\\Posts): " + 0;
            else
                statMsg = "User: " + userName + "\r\nTotal Public Action(Threads\\Posts): " + res;
            return statMsg;
        }

        #endregion

        //-- get stuff
        public Forum getForum(User user, int forumid)
        {//return null if the forumid is not there

            //check that forum exist
            Boolean hasForum = false;
            SortedDictionary<int, Forum> pair = database.getForums();
            if (!pair.ContainsKey(forumid))
                return null;
            /*foreach (int id in database.getForums().Keys)
            {
                if (id == forumid)
                    hasForum = true;
            }
            if (hasForum == false)
                return null;*/

            if (user != null)
            {
                this.userPositions[user.getUserName() + " " + forumid].thread = -1;
                this.userPositions[user.getUserName() + " " + forumid].subForum = -1;
            }
            Forum ans = database.getForum(forumid);
            return ans;
        }
        public SubForum getSubForum(User user, int forumid, int subforumid)
        {//return null if the forumid or subforumid is not currect

            if (user != null)
            {
                try
                {
                    this.userPositions[user.getUserName() + " " + forumid].subForum = subforumid;
                    this.userPositions[user.getUserName() + " " + forumid].thread = -1;
                }
                catch (Exception e)
                {
                    Console.WriteLine(user.getUserName() + " is missing from the user position");
                    Logger.log(string.Format(user.getUserName() + " is missing from the user position"));
                }

                //check user login
                if (CheckIfUserLogin(user, forumid) == false)
                    return null;
            }
            SubForum ans;
            try
            {
                ans = database.getForum(forumid).getSubForum(subforumid);
            }
            catch
            {
                return null;
            }
            return ans;
        }

        public Thread getThread(User user, int forumid, int threadid, int subForumId = 0)
        {
            int tmpSF = subForumId;
            if (subForumId == 0)
            {
                tmpSF = this.userPositions[user.getUserName() + " " + forumid].subForum;
                this.userPositions[user.getUserName() + " " + forumid].thread = threadid;
            }

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            Thread ans;
            try
            {
                ans = database.getForum(forumid).getSubForum(tmpSF).getThread(threadid);
            }
            catch
            {
                return null;
            }
            return ans;
        }

        public Thread GetWebThread(int forumID, int subForumID, int threadID)
        {
            return database.getForum(forumID).getSubForum(subForumID).getThread(threadID);
        }

        public Post getPost(User user, int forumid, int subforumid, int threadid, int postid)
        {

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return null;

            Post ans = database.getForum(forumid).getSubForum(subforumid).getThread(threadid).getPost(postid);
            return ans;
        }



        //Statistic Functions-----------------------------

        public List<string> getUserList(User user)
        {//return the list of the users
            //return empty list if there is problem



            List<string> userlist = new List<string>();
            foreach (Forum forum in database.getForums().Values)
            {
                if (forum != null)
                    foreach (string username in database.getForumUsers(forum.getId()).Keys)
                        userlist.Add(username);
            }


            return userlist;
        }

        public SortedDictionary<int, Forum> getAllForumsData(User user)
        {//return all the forums at sorted dictionary
            SortedDictionary<int, Forum> ans = database.getForums();
            return ans;
        }
        //return the database

        public SortedDictionary<string, User> getForumUsers(int forumid)
        {//return empty sorted if have problem
            SortedDictionary<string, User> ans = new SortedDictionary<string, User>();
            Forum forum = database.getForum(forumid);
            if (forum != null)
            {
                foreach (User user in database.getForumUsers(forumid).Values)
                {
                    if (user != null)
                    {
                        ans.Add(user.getUserName(), user);
                    }
                }
            }
            return ans;
        }


        //User Position methods
        public int getUserForum(string userName, int forumId)
        {
            return this.userPositions[userName + " " + forumId].forum;
        }

        public int getUserSub(string userName, int forumId)
        {
            return this.userPositions[userName + " " + forumId].subForum;
        }

        public int getUserThread(string userName, int forumId)
        {
            return this.userPositions[userName + " " + forumId].thread;
        }


        //return the users of the forum

        //return the number of the common users at diffrent forums

        public Boolean setForumName(User user, int forumid, string newforumname)
        {//set the forum name



            //check if the string is null or the client is not gilad so he cant change the name
            if (newforumname == null || user == null || (!user.getUserName().Equals(database.getDirector().getName())))
                return false;
            database.setForumTitle(forumid, newforumname);
            return true;
        }


        public string getForumName(User user, int forumid)
        //public string getForumName(Client client)
        {//return the forum name
            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return "";

            return database.getForumTitle(forumid);
        }



        public Boolean IsRegister(User user, int forumid)
        {//return true if the client is register
            //return false if not
            //check user login

            if (user == null || (!CheckIfUserMember(forumid, user.getUserName())))
                return false;

            return true;
        }

        public Boolean islogin(User user, int forumid)
        {//check if the client is login right now
            //return true if yes , false if no.
            //add now 25/6/13
            //check if director
            if (user.getUserName().Equals(database.getDirector().getUserName()))
                return this.DirectorIsLogin;

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;


            Boolean ans = true;

            if (user == null || forumsuserlist == null || forumid < 0)
                return false;
            string usernamewithforumid = user.getUserName() + "" + forumid;
            if (forumsuserlist.Contains(usernamewithforumid) == false)
                return false;

            return ans;
        }

        public Boolean logout(User user, int forumid)
        {

            this.userPositions.Remove(user.getUserName() + " " + forumid);

            //check user login
            if (CheckIfUserLogin(user, forumid) == false)
                return false;

            if (user == null || forumsuserlist == null || forumid < 0)
                return false;
            //check if its guest
            if (user.getName().Equals("") && user.getPassword().Equals(""))
            {
                forumsuserlist.Remove(user.getUserName());
                Console.WriteLine(user.getUserName() + " is logout");
                Logger.log(string.Format(user.getUserName() + " is logout"));
                return true;
            }
            //if its director 
            if (user.getUserName().Equals(database.getDirector().getUserName()))
            {
                DirectorIsLogin = false;
                Console.WriteLine("Director {0} has logout", user.getUserName());
                Logger.log(string.Format("Director {0} has logout", user.getUserName()));
                return true;
            }


            string usernamewithforumid = user.getUserName() + "" + forumid;
            if (forumsuserlist.Contains(usernamewithforumid) == false)
                return false;
            if (forumsuserlist.Remove(usernamewithforumid) == false)
                return false;
            Console.WriteLine("User {0} is logout from forum {1}", user.getUserName(), database.getForumTitle(forumid));
            Logger.log(string.Format("User {0} is logout from forum {1}", user.getUserName(), database.getForumTitle(forumid)));
            return true;
        }

        public Boolean login(int forumid, string username, string password)
        {//"" guest is a user with "" user name and "" password
            if (forumid < 0)
                return false;

            if (password.Equals(""))
            //if its guest
            {
                forumsuserlist.Add(username + forumid);


                this.userPositions.Add(username + " " + forumid, new UserPosition(new User(username, "", "", "0", ""), forumid));
                this.userPositions[username + " " + forumid].subForum = -1;
                this.userPositions[username + " " + forumid].thread = -1;

                Console.WriteLine("Guest has loged in");
                try
                {
                    Logger.log(string.Format("Guest has loged in"));
                }
                catch (Exception e)
                {
                }
                return true;
            }



            string usernamewithforumid = username + "" + forumid;
            User user = getuser(forumid, username);



            //if its the director
            if (username.Equals(database.getDirector().getUserName()) && Server.Security.passwordVerification(username, password, user.getPassword()))
            {
                DirectorIsLogin = true;

                this.userPositions.Add(username + " " + forumid, new UserPosition(user, forumid));
                this.userPositions[username + " " + forumid].subForum = -1;
                this.userPositions[username + " " + forumid].thread = -1;

                Console.WriteLine("Director {0} has loged in", username);
                Console.WriteLine("Guest has loged in");
                try
                {
                    Logger.log(string.Format("Director {0} has loged in", username));
                }
                catch (Exception e)
                {
                }
                
                return true;
            }

            //string usernamewithforumid = username + "" + forumid;
            //User user = getuser(forumid, username);

            //check the password is ok
            //int pass = int.Parse(password);

            if (user == null)
                return false;



            // *********** Gilad's addition ************
            if (!Server.Security.passwordVerification(username, password, user.getPassword()))
            {
                return false;
            }
            // *********** End Gilad's addition ************


            /*
            if (user.getPassword() != password)
                return false;

            password = Server.Security.passwordEncryption(username, password);
            if (!user.getPassword().Equals(password))
                return false;            */

            this.userPositions.Add(username + " " + forumid, new UserPosition(user, forumid));
            this.userPositions[username + " " + forumid].subForum = -1;
            this.userPositions[username + " " + forumid].thread = -1;


            forumsuserlist.Add(usernamewithforumid);
            Console.WriteLine("User {0} has loged in to forum {1}", username, database.getForumTitle(forumid));
            Logger.log(string.Format("User {0} has loged in to forum {1}", username, database.getForumTitle(forumid)));
            return true;
        }

        public bool webLogin(int forumid, string username, string password)
        {
            User user = getuser(forumid, username);
            if (user == null)
                return false;
            if (!Server.Security.passwordVerification(username, password, user.getPassword()))
            {
                return false;
            }
            else return true;
        }


        //not in use?
        public Boolean login(User user, int forumid)
        {//"" guest is a user with "" user name and "" password

            return login(forumid, user.getUserName(), user.getPassword());
            /*
            if (user == null || forumsuserlist == null || forumid < 0)
                return false;
            
            if (user.getUserName().Equals("") && user.getPassword().Equals(""))
            //if its guest
            {
                Console.WriteLine("Guest is login");
                Logger.log(string.Format("Guest is login"));
                return true;
            }

            //if its the director
            if (user.getUserName().Equals(database.getDirector().getUserName()))
            {
                DirectorIsLogin = true;
                Console.WriteLine("Director {0} is login", user.getUserName());
                Logger.log(string.Format("Director {0} is login", user.getUserName()));
                return true;
            }
            User theuser = getuser(forumid, user.getUserName());

            //check the password is ok
            //int pass = user.getPassword();
            if (theuser.getPassword() != user.getPassword())
                return false;

            string usernamewithforumid = user.getUserName() + "" + forumid;
            forumsuserlist.Add(usernamewithforumid);
            Console.WriteLine("User {0} is login to forumname{1}", user.getUserName(), database.getForumTitle(forumid));
            Logger.log(string.Format("User {0} is login to forumname{1}", user.getUserName(), database.getForumTitle(forumid)));
            return true;
             */
        }

        public string getAllStatistic(User user, int forumid)
        {
            string res = "";

            foreach (KeyValuePair<int, SubForum> pair in database.getForum(forumid).getSubForums())
            {
                res = res + "\r\n" + this.getstringCountsubForumMsg(user, forumid, pair.Key);
            }
            foreach (KeyValuePair<string, User> pair in database.getForum(forumid).getUsers())
            {
                res = res + "\r\n" + this.getstringCountMemberMsg(user, forumid, pair.Key);
            }
            foreach (KeyValuePair<int, SubForum> pairsubforum in database.getForum(forumid).getSubForums())
            {
                int subforumid = pairsubforum.Key;
                foreach (KeyValuePair<int, Thread> pairthread in pairsubforum.Value.getThreads())
                {
                    int threadid = pairthread.Key;
                    res = res + "\r\n the member that respond to thread " + pairthread.Key + " :" + this.getMembersResponedToThread(user, forumid, subforumid, threadid);
                }
            }
            return res;
        }

        #endregion

        #region private methood

        private Boolean CheckIfDirectorLogin(User user)
        {
            if (user == null)
                return false;


            return DirectorIsLogin;
        }

        private Boolean CheckIfUserLogin(User user, int forumid)
        {
            if (user == null || forumid < 0)
                return false;
            //if its director
            if (user.getUserName().Equals(database.getDirector().getUserName()))
                return CheckIfDirectorLogin(user);

            string usernamewithforumid = user.getUserName() + "" + forumid;
            if (forumsuserlist.Contains(usernamewithforumid) == false)
                return false;
            return true;
        }

        private string getMembersResponedToThread(User user, int forumid, int subforumid, int threadid)
        {//function that will return at a string all the members that respond to his thread
            string res = "";

            SortedDictionary<int, Post> allpost = database.getThreadPosts(forumid, subforumid, threadid);
            if (allpost != null)
                foreach (Post post in allpost.Values)
                {
                    if (post != null)
                    {
                        if (res.Equals(""))
                            res = post.getUser().getName();
                        else
                            res = res + " , " + post.getUser().getName();
                    }
                }


            return res;
        }

        //function that check if username is user at the forum
        private Boolean CheckIfUserMember(int forumid, string username)
        {
            if (database.isForumUser(forumid, username))
                return true;


            return false;
        }
        //function that create user from the client

        /*
        private User CreateUserFromClient(Client client)
        {
            int pass = int.Parse(client.PassWord);
            User user=new User(client.Name,client.FirstName,client.LastName,pass,client.Email);
            return user;
        }
        */


        //function to check if username has the premission to change/remove moderator
        private bool CheckPermissionChangeModerator(int forumid, string managerusername)
        {// only manager of the forum can change the moderator

            User manager = database.getForumAdmin(forumid);
            User director = database.getDirector();
            if (director.getUserName().Equals(managerusername) == true)
                return true;
            if (manager == null)
                return false;
            if (managerusername.Equals(manager.getUserName()) == true)
                return true;
            return false;

        }
        #endregion

        public int getSubForumID(int forumid, string subforum)
        {
            int res = -1;
            Forum forum = database.getForum(forumid);
            if (forum == null)
                return res;

            foreach (KeyValuePair<int, SubForum> pair in forum.getSubForums())
            {
                if (pair.Value.getTitle().Equals(subforum))
                    return pair.Key;
            }
            return res;


        }

        public User getuser(int forumid, string nick)
        {
            return database.getUser(forumid, nick);
        }

        public User getdirector()
        {
            return database.getDirector();
            //int pass = int.Parse(adminPassword);


            /* *********** Gilad's addition ************
            if (Server.Security.passwordVerification(admin, adminPassword, res.getPassword()))
            {
                return res;
            }
            // *********** End Gilad's addition ************


            /*
            if (res.getUserName().Equals(admin) && res.getPassword() == adminPassword)
                return res;
            */

        }

        public List<string> getUserLists()
        {

            //return the user
            return forumsuserlist;
        }


        //public bool isAllowedActionInForum(int forum)
        //{
        //    bool action=false;
        //    switch (database.getForumType(forum))
        //    {
        //        case 1:
        //            action = true;
        //            break;
        //        case 2:
        //            action = false;
        //            break;
        //    }

        //    return action;
        //}



        //public int getForumPolicy(int forum)
        //{
        //    return database.getForumType(forum);
        //}


        public int canAddMod(int forum)
        {
            return database.getAddModeratorPolicy(forum);
        }

        public int emailAuth(int forum)
        {
            return database.getEmailPolicy(forum);
        }

        public int notificationPolicy(int forum)
        {
            return database.getNotificationPolicy(forum);
        }

        public int canRemoveMod(int forum)
        {
            return database.getRemoveModeratorPolicy(forum);
        }

        public int canDelPosts(int forum)
        {
            return database.getRemovePostThreadPolicy(forum);
        }

        public int numOfMes(int forum,string sub, string user)
        {
            return database.getUserNumOfMesInSF(forum ,getSubForumID(forum, sub), user);
        }

        public int userSeniority(int forum, User user)
        {
            return (int)(DateTime.Now - database.getUserCreationTime(forum, user.getUserName())).TotalDays;
        }

        public List<string> getForumWords(int forum)
        {

            return database.getForbiddenWords(forum).Values.ToList();
        }


        public bool checkMessage(string message, int forum)
        {
            if (this.cachedForum != forum)
            {
                this.cachedForum = forum;
                this.cachedForbiddenWords = this.getForumWords(forum);
            }

            foreach (string fWord in this.cachedForbiddenWords)
            {
                if (message.Contains(fWord) && String.Compare(fWord, "") != 0)
                    return false;
            }
            return true;

        }


        public void sendRegisterCode(string name, string last, string nick, string pass, string email, int forumid)
        {

            //this is a generic email code, dont ask me what it does, I have no idea 
            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential("forumsawesome@gmail.com", "justtooawesome")
            };
            using (var message = new MailMessage("forumsawesome@gmail.com", email)
            {
                Subject = "Registration code for Forum " + this.database.getForumTitle(forumid),
                Body = nick + "\n\n Welcome to " + this.database.getForumTitle(forumid) + ", please copy this code to the registration window to proceed : \n" + email.GetHashCode().ToString() +
                "\n\n\n\n\n\n" + "<a href=\"http://i228.photobucket.com/albums/ee298/Swordspin/mars/forums_zpsea436161.png\"><img src=\"http://i228.photobucket.com/albums/ee298/Swordspin/mars/forums_zpsea436161.png\" align=\"left\" /></a>"

            })
            {
                smtp.Send(message);
            }

        }


        public bool confirmCode(string name, string last, string nick, string pass, string email, int forumid, string code)
        {
            string g = email.GetHashCode().ToString();
            return (String.Compare(code, email.GetHashCode().ToString()) == 0);
        }


        public int getForumIDByName(string forumname)
        {
            foreach (KeyValuePair<int, Forum> pair in database.getForums())
            {
                if (pair.Value.getTitle().Equals(forumname))
                    return pair.Key;
            }
            return -1;
        }

        public bool RemoveForum(int forumid)
        {
            return database.removeForum(forumid);
        }

        public bool RemoveUser(int forumid, string username)
        {
            return database.removeUser(forumid, username);
        }

        public int getThreadID2(int forumid, string title, string body)
        {
            //return 500;
            int res = -1;
            Forum forum = database.getForum(forumid);
            if (forum == null)
                return res;

            foreach (KeyValuePair<int, SubForum> pair in forum.getSubForums())
            {
                foreach (KeyValuePair<int, Thread> pairthread in pair.Value.getThreads())
                {

                    if (pairthread.Value.getTitle().Equals(title) && pairthread.Value.getBody().Equals(body))
                        return pairthread.Value.getId();
                }
            }
            return res;
        }

        public int getPostid(int forumid, string title, string body)
        {
            int res = -1;
            Forum forum = database.getForum(forumid);
            if (forum == null)
                return res;

            foreach (KeyValuePair<int, SubForum> pair in forum.getSubForums())
            {
                foreach (KeyValuePair<int, Thread> pairthread in pair.Value.getThreads())
                {
                    foreach (KeyValuePair<int, Post> pairpost in pairthread.Value.getPosts())
                    {
                        if (pairpost.Value.getTitle().Equals(title) && pairpost.Value.getBody().Equals(body))
                            return pairpost.Value.getID();
                    }
                }
            }
            return res;
        }

        internal bool isMod(int forum, User user)
        {
            return this.database.isSubForumModerator(forum, userPositions[user.getUserName() + " " + forum].subForum, user);
        }

        public List<User> getActiveUsers(int forum, int sub)
        {
            return this.database.getPublishedUsers(forum, sub);
        }

        public void createHTMLfromDatabase()
        {
            string path = Directory.GetCurrentDirectory();
            path = System.IO.Path.Combine(path, "Base");
            System.IO.Directory.CreateDirectory(path);//creating main folder
            foreach (Forum forum in this.database.getForums().Values.ToList())
                createHTMLfromForum(forum,path);
            Console.WriteLine("HTML site was created from the Database");
            Logger.log(string.Format("HTML site was created from the Database"));
        }

        public void createHTMLfromForum(Forum forum, string path)
        {
            string forumPath = System.IO.Path.Combine(path, forum.getId().ToString());
            System.IO.Directory.CreateDirectory(forumPath);//creating a forum folder
            using (System.IO.FileStream fs = System.IO.File.Create(System.IO.Path.Combine(forumPath, forum.getId().ToString() + ".html")))//creating forum html file
            {
                System.Text.UTF8Encoding UTFEncoder = new System.Text.UTF8Encoding();
                var uri = new System.Uri(forumPath +"\\"+ forum.getId().ToString() +".html");
                var forumURI = uri.AbsoluteUri;
                writeToFS(UTFEncoder.GetBytes("<A HREF =\"" + forumURI + "\">-home</A>\r\n"), fs);
                writeToFS( UTFEncoder.GetBytes("<h1 class=\"title\">Forum " + forum.getTitle().ToString() + "\r\n</h1>"),fs);
                writeToFS( UTFEncoder.GetBytes("<p>\r\n\r\nSub Forums:</p>\r\n"),fs);
                writeToFS(UTFEncoder.GetBytes("<ul>\r\n"), fs);
                SortedDictionary<int, SubForum> subs = forum.getSubForums();
                for (int i = 0; i < subs.Count; i++)
                {
                    uri = new System.Uri(forumPath + "\\" + subs.ElementAt(i).Value.getId() + "\\" + subs.ElementAt(i).Value.getId() + ".html");
                    var converted = uri.AbsoluteUri;
                    writeToFS(UTFEncoder.GetBytes("<li><A HREF =\""+converted +"\">"+ subs.ElementAt(i).Value.getTitle() + "</li>\r\n"), fs);
                    createHTMLfromSub(subs.ElementAt(i).Value, forumPath, forumURI);
                }
                writeToFS(UTFEncoder.GetBytes("</ul>\r\n"), fs);
            }
        }

        public void createHTMLfromSub(SubForum sub, string path, string forumURI)
        {
            string subPath = System.IO.Path.Combine(path, sub.getId().ToString());
            System.IO.Directory.CreateDirectory(subPath);//creating a forum folder
            using (System.IO.FileStream fs = System.IO.File.Create(System.IO.Path.Combine(subPath, sub.getId().ToString() + ".html")))//creating forum html file
            {
                System.Text.UTF8Encoding UTFEncoder = new System.Text.UTF8Encoding();
                writeToFS(UTFEncoder.GetBytes("<A HREF =\"" + forumURI + "\">-home</A>\r\n"), fs);
                writeToFS(UTFEncoder.GetBytes("<h1 class=\"title\">Sub Forum " + sub.getTitle().ToString() + "\r\n</h1>"), fs);
                writeToFS(UTFEncoder.GetBytes("<p>\r\n\r\nThreads:</p>\r\n"), fs);
                writeToFS(UTFEncoder.GetBytes("<ul>\r\n"), fs);
                SortedDictionary<int, Thread> threads = sub.getThreads();
                for (int i = 0; i < threads.Count; i++)
                {
                    var uri = new System.Uri(subPath + "\\" + threads.ElementAt(i).Value.getId() + "\\" + threads.ElementAt(i).Value.getId() + ".html");
                    var converted = uri.AbsoluteUri;
                    writeToFS(UTFEncoder.GetBytes("<li><A HREF =\"" + converted + "\">" + threads.ElementAt(i).Value.getTitle() + "</li>\r\n"), fs);
                    createHTMLfromThread(threads.ElementAt(i).Value, subPath, forumURI);
                }
                writeToFS(UTFEncoder.GetBytes("</ul>\r\n"), fs);
            }
        }

        public void createHTMLfromThread(Thread tread, string path, string forumURI)
        {
            string threadPath = System.IO.Path.Combine(path, tread.getId().ToString());
            System.IO.Directory.CreateDirectory(threadPath);//creating a forum folder
            using (System.IO.FileStream fs = System.IO.File.Create(System.IO.Path.Combine(threadPath, tread.getId().ToString() + ".html")))//creating forum html file
            {
                System.Text.UTF8Encoding UTFEncoder = new System.Text.UTF8Encoding();
                writeToFS(UTFEncoder.GetBytes("<A HREF =\"" + forumURI + "\">-home</A>\r\n"), fs);
                writeToFS(UTFEncoder.GetBytes("<h1 class=\"title\">Thread " + tread.getTitle().ToString() + "\r\n</h1>"), fs);
                writeToFS(UTFEncoder.GetBytes("<p>Thread " + tread.getBody().ToString() + "[" + tread.getUser().getUserName() + "]\r\n</p>"), fs);
                writeToFS(UTFEncoder.GetBytes("<p>\r\n\r\nPosts:</p>\r\n"), fs);
                writeToFS(UTFEncoder.GetBytes("<ul>\r\n"), fs);
                SortedDictionary<int, Post> posts = tread.getPosts();
                for (int i = 0; i < posts.Count; i++)
                {
                    writeToFS(UTFEncoder.GetBytes("<li>" + posts.ElementAt(i).Value.getTitle() + ":<p>\r\n" + posts.ElementAt(i).Value.getBody() + "[" + posts.ElementAt(i).Value.getUser().getUserName() + "]</p></li>\r\n"), fs);
                }
                writeToFS(UTFEncoder.GetBytes("</ul>\r\n"), fs);

                writeToFS(UTFEncoder.GetBytes("<hr><h2>Write Comment</h2><table width=\"70%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"> <tr> <td>name:</td> <td colspan=\"2\"><input type=\"text\" name=\"name\"></td> </tr><tr> <td>password:</td> <td colspan=\"2\"><input type=\"text\" name=\"password\"></td></tr><tr> <td>comments:</td> <td colspan=\"2\"><textarea name=\"comment\" cols=\"40\" rows=\"5\"></textarea></td></tr><tr><td>&nbsp;</td><td colspan=\"2\"><input type=\"submit\" name=\"Post\" value=\"Post\"></td></tr></table> "), fs);
            }
        }

        public void writeToFS(byte[] line, System.IO.FileStream fs)
        {
            foreach(byte by in line)
            {
                fs.WriteByte(by);
            }
        }

    }




}

//private class to track users position
class UserPosition
{
    public User user { set; get; }
    public int forum { set; get; }
    public int subForum { set; get; }
    public int thread { set; get; }

    public UserPosition(User u, int forum)
    {
        this.user = u;
        this.forum = forum;
    }


}

       
